package com.godme.gateway.endpoint;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.godme.gateway.sentinel.UserEndpointSentinelResource;
import com.godme.service.user.UserManager;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/user")
public class UserEndpoint {

    @DubboReference
    UserManager userManager;


    @PostMapping("/check/{token}")
    @SentinelResource(value = "check", fallback = "checkFallback", blockHandler = "checkBlock", fallbackClass = UserEndpointSentinelResource.class, blockHandlerClass = UserEndpointSentinelResource.class)
    public String check(@PathVariable("token") String token){
        return userManager.check(token);
    }


    @PostMapping("/login/{mail}/{password}")
    @SentinelResource(value = "login", fallback = "loginFallback", blockHandler = "loginBlock", fallbackClass = UserEndpointSentinelResource.class, blockHandlerClass = UserEndpointSentinelResource.class)
    public boolean login(HttpServletResponse response, @PathVariable("mail") String mail, @PathVariable("password") String password){
        boolean isRegister = userManager.auth(mail, password);
        if(isRegister){
            Cookie cookie = new Cookie("token", userManager.sign(mail, password));
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return isRegister;
    }

    @PostMapping("/register/{mail}/{password}/{code}")
    @SentinelResource(value = "register", fallback = "registerFallback", blockHandler = "registerBlock", fallbackClass = UserEndpointSentinelResource.class, blockHandlerClass = UserEndpointSentinelResource.class)
    public boolean register(@PathVariable("mail") String mail, @PathVariable("password") String password, @PathVariable("code") String code){
        return userManager.register(mail, password, code);
    }
}
